<!--
  * 云喇叭管理
-->
<template>
  <!---------- 查询表单form begin ----------->

  <a-form class="smart-query-form">
    <a-row class="smart-query-form-row">
      <a-form-item label="厂商名称" class="smart-query-form-item">
        <CustomSelect
          style="width: 180px"
          v-model:value="queryForm.manufacturerId"
          :placeholder="'请选择厂商名称'"
          queryParamKey="manufacturerName"
          :api="manufacturerApi.page"
          @change="(...data) => handleChange(data)"
          label-field="manufacturerName,id"
        />
      </a-form-item>
      <a-form-item label="产品型号" class="smart-query-form-item" v-if="queryForm.manufacturerId">
        <CustomSelect
          style="width: 180px"
          v-model:value="queryForm.deviceModelId"
          :placeholder="'请选择产品型号'"
          queryParamKey="deviceModelName"
          :api="deviceModelApi.page"
          :queryParams="{
            manufacturerId: queryForm.manufacturerId,
            deviceType: cloudDevice,
          }"
          label-field="deviceModelName,id"
        />
      </a-form-item>
      <a-form-item label="设备编号" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.id" placeholder="输入设备编号" />
      </a-form-item>
      <a-form-item label="商户名称" class="smart-query-form-item">
        <CustomSelect
          style="width: 200px"
          v-model:value="queryForm.merchantId"
          :placeholder="'请选择'"
          :api="merchantApi.page"
          :queryParams="merchantParams"
          queryParamKey="companyNameLeftLike"
          labelField="companyName,no"
        />
      </a-form-item>
      <a-form-item label="设备状态" class="smart-query-form-item">
        <a-select v-model:value="queryForm.status" style="width: 180px" allowClear :options="DEVICE_STATUS" placeholder="请选择设备状态" />
      </a-form-item>
      <a-form-item label="设备SN" class="smart-query-form-item">
        <a-input style="width: 200px" v-model:value="queryForm.sn" placeholder="输入设备SN" />
      </a-form-item>
      <a-form-item class="smart-query-form-item">
        <a-button type="primary" @click="onSearch">
          <template #icon>
            <SearchOutlined />
          </template>
          查询
        </a-button>
        <a-button @click="resetQuery" class="smart-margin-left10">
          <template #icon>
            <ReloadOutlined />
          </template>
          重置
        </a-button>
      </a-form-item>
    </a-row>
  </a-form>
  <!---------- 查询表单form end ----------->

  <a-card size="small" :bordered="false" :hoverable="true">
    <!---------- 表格操作行 begin ----------->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-title">数据列表</div>
      <div class="smart-table-operate-block">
        <a-button @click="showForm" type="primary" size="small">
          <template #icon>
            <PlusOutlined />
          </template>
          新增
        </a-button>
      </div>
    </a-row>
    <!---------- 表格操作行 end ----------->

    <!---------- 表格 begin ----------->
    <a-table size="small" :dataSource="tableData" :columns="columns" rowKey="id" bordered :loading="tableLoading" :pagination="false" />
    <!---------- 表格 end ----------->

    <div class="smart-query-table-page">
      <a-pagination
        showSizeChanger
        showQuickJumper
        show-less-items
        :pageSizeOptions="PAGE_SIZE_OPTIONS"
        :defaultPageSize="queryForm.pageSize"
        v-model:current="queryForm.pageNo"
        v-model:pageSize="queryForm.pageSize"
        :total="total"
        @change="queryData"
        @showSizeChange="queryData"
        :show-total="(total) => `共${total}条`"
      />
    </div>
  </a-card>

  <CloudSpeakerForm v-model:open="cloudSpeakerOptions.open" :formType="cloudSpeakerOptions.type" :rowData="cloudSpeakerOptions.data" @ok="onSearch" />
  <CloudTestForm v-model:open="testOptions.open" :formType="testOptions.type" :rowData="testOptions.data" />
  <SelectMch v-model:open="bindMchOptions.open" @ok="bindMchOk" />
</template>
<script setup>
  import { reactive, ref, onMounted, computed, getCurrentInstance, h } from 'vue'
  import { manufacturerApi } from '/@/api/business/b-operation/manufacturer/index'
  import { merchantApi } from '/@/api/business/b-operation/merchant/merchant-api.js'
  import { deviceApi } from '/@/api/business/b-operation/device'
  import { deviceModelApi } from '/@/api/business/b-operation/device-model'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import { PAGE_SIZE_OPTIONS } from '/@/constants/common-const'
  import { smartSentry } from '/@/lib/smart-sentry'
  import { Button, Switch, Modal, message } from 'ant-design-vue'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { selectDictLabel, privilege } from '/@/utils/common'
  import { DEVICE_STATUS, DEVICE_TYPE, START_STOP } from '/@/constants/dict'
  import CloudSpeakerForm from './cloud-speaker-form.vue'
  import CloudTestForm from './cloud-test-form.vue'
  import SelectMch from '/@/components/business/comment/SelectMch.vue'
  import { isEmpty } from 'lodash'
  import { useRoute } from 'vue-router'
  const route = useRoute()
  const { proxy } = getCurrentInstance()
  // ---------------------------- 表格列 ----------------------------
  const cloudDevice = computed(() => {
    // 0云喇叭 1云打印
    return route.path.includes('cloud-speaker') ? 0 : 1
  })

  const columns = ref([
    {
      title: '序号',
      dataIndex: 'index',
      width: 60,
      customRender: ({ index }) => {
        return (queryForm.pageNo - 1) * queryForm.pageSize + index + 1
      },
    },
    {
      title: '设备编号',
      dataIndex: 'id',
      ellipsis: true,
    },
    {
      title: '设备类型',
      dataIndex: 'deviceType',
      ellipsis: true,
      customRender: (column) => selectDictLabel(DEVICE_TYPE, column.text),
    },
    {
      title: '设备SN',
      dataIndex: 'sn',
      ellipsis: true,
    },
    {
      title: '厂商名称',
      dataIndex: 'manufacturerName',
      ellipsis: true,
    },
    {
      title: '产品型号',
      dataIndex: 'deviceModelName',
      ellipsis: true,
    },
    {
      title: '商户名称',
      dataIndex: 'merchantName',
      ellipsis: true,
    },
    {
      title: '门店名称',
      dataIndex: 'storeName',
      ellipsis: true,
    },
    {
      title: '设备状态',
      dataIndex: 'status',
      customRender: (column) => (column.text == 1 ? '正常' : '未激活'),
      ellipsis: true,
    },
    {
      title: '是否启用',
      dataIndex: 'isOpen',
      customRender: (column) => (column.text == 1 ? '是' : '否'),
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'cTime',
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      minWidth: 180,
      customRender: ({ record }) => {
        return h('div', [
          isEmpty(record.merchantName)
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    showBindMch(record)
                  },
                },
                '绑定',
              )
            : h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    showUnBindMch(record)
                  },
                },
                '解绑',
              ),
          // privilege('manufacturer:find_id')
          h(
            Button,
            {
              type: 'link',
              size: 'small',
              onClick: () => {
                showForm(record, 'view')
              },
            },
            '详情',
          ),
          isEmpty(record.merchantName)
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    delRow(record)
                  },
                },
                '删除',
              )
            : '',
          isEmpty(record.merchantName)
            ? h(
                Button,
                {
                  type: 'link',
                  size: 'small',
                  onClick: () => {
                    testRow(record)
                  },
                },
                '测试',
              )
            : '',
        ])
      },
    },
  ])

  // ---------------------------- 查询数据表单和方法 ----------------------------

  const queryFormState = {
    manufacturerName: undefined,
    manufacturerId: undefined,
    deviceModelId: undefined,
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = reactive({ ...queryFormState })
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.pageSize
    Object.assign(queryForm, queryFormState)
    queryForm.pageSize = pageSize
    queryData()
  }

  // 搜索
  function onSearch() {
    queryForm.pageNo = 1
    queryData()
  }

  /* 切换厂商 */
  function handleChange(data) {
    queryForm.deviceModelId = undefined
  }

  // 查询数据
  async function queryData() {
    tableLoading.value = true
    let queryParams = { ...queryForm, deviceType: cloudDevice.value }
    try {
      let queryResult = await deviceApi.page(queryParams)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  // const getBusinessName = (value) => {
  //   const item = CHANNEL_BUSINESS_TYPE.find((item) => item.value === value)
  //   return item ? item.itemName : null
  // }

  onMounted(() => {
    queryData()
    // getBusinessList()
  })

  // ---------------------------- 添加/修改 ----------------------------
  const cloudSpeakerOptions = ref({
    open: false,
    data: null,
    type: 'add',
  })

  function showForm(data, type) {
    cloudSpeakerOptions.value.open = true
    cloudSpeakerOptions.value.data = data
    cloudSpeakerOptions.value.type = type
  }

  // 绑定商户
  const bindMchOptions = ref({
    open: false,
    data: null,
  })
  const showBindMch = (data) => {
    bindMchOptions.value.open = true
    bindMchOptions.value.data = data
  }
  const bindMchOk = (val) => {
    if (isEmpty(val)) return
    const data = { merchantName: val[0].companyAbbrName, no: val[0].no, merchantId: val[0].id, id: bindMchOptions.value.data.id }
    deviceApi.bindAndUnbind(data).then((res) => {
      bindMchOptions.value.open = false
      onSearch()
    })
  }

  // 解绑商户
  const showUnBindMch = (record) => {
    Modal.confirm({
      title: '提示',
      content: '确定要解绑该商户吗?',
      okText: '解绑',
      okType: 'danger',
      async onOk() {
        const data = { merchantName: null, merchantId: null, id: record.id }
        deviceApi.bindAndUnbind(data).then((res) => {
          onSearch()
        })
      },
      cancelText: '取消',
      onCancel() {},
    })
  }
  // ---------------------------- 批量删除 ----------------------------

  // 删除
  async function delRow(record) {
    Modal.confirm({
      title: '提示',
      content: '确定要删除该数据吗?',
      okText: '删除',
      okType: 'danger',
      async onOk() {
        rowDelete(record)
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  //请求删除
  async function rowDelete(record) {
    try {
      SmartLoading.show()
      await deviceApi.delete({ id: record.id })
      message.success('删除成功')
      queryData()
    } catch (e) {
      console.log(e)
      smartSentry.captureError(e)
    } finally {
      SmartLoading.hide()
    }
  }

  // 测试设备
  const testOptions = ref({
    open: false,
    data: null,
  })
  const testRow = (record) => {
    testOptions.value = { open: true, data: record }
  }
  // handleTestOk
</script>

<style lang="less" scoped>
  .notice-alert {
    margin-bottom: 16px;

    :deep(.ant-alert) {
      &.ant-alert-warning {
        background-color: #f59a23;
        border: none;
        padding: 16px 24px;

        .ant-alert-message {
          color: #ffffff;
        }
      }
    }
  }

  .smart-table-btn-block {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    justify-content: space-between;
  }

  .smart-table-title {
    font-size: 16px;
    font-weight: 500;
  }

  .smart-table-operate-block {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .custom-modal {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    z-index: 1000;
  }

  .modal-content {
    width: 400px;
    padding: 20px;
    background-color: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
    text-align: center;
  }

  #modal-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 10px;
  }

  .modal-message {
    display: flex;
    align-items: center; /* 垂直居中 */
    margin-bottom: 20px;
  }

  #modal-icon {
    color: #f0ad4e; /* 警告图标的颜色 */
    font-size: 24px;
    margin-right: 10px;
  }

  #modal-content {
    font-size: 14px;
    color: #333;
  }

  .modal-buttons {
    display: flex;
    justify-content: center;
    gap: 10px;
  }

  #modal-ok {
    background-color: #007bff;
    color: #fff;
    border: none;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
  }

  #modal-cancel {
    background-color: #f0f0f0;
    color: #333;
    border: 1px solid #ccc;
    padding: 8px 20px;
    border-radius: 4px;
    cursor: pointer;
  }
</style>
